const express = require('express');
const multer = require('multer');
const path = require('path')

const app = express();

// 设置 multer 存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/') // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop())
    }
});

const upload = multer({ storage: storage });

// 将 uploads 目录设置为静态资源目录
app.use('/uploadImagines', express.static('uploads'));

// 创建上传接口
app.post('/upload', upload.single('file'), (req, res) => {
    console.log('收到了');
    if (!req.file) {
        return res.status(400).send('No file uploaded.');
    }
    // 构建文件的 URL
    const fileUrl = `${req.protocol}://${req.get('host')}/uploadImagines/${req.file.filename}`;
    res.header('path',fileUrl)
    return res.json({'path':fileUrl});
});

// 设置端口
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
